import * as bajaService from '@/services/bajaService';
import memoryUtils from '@/utils/memoryUtils';

export default {
  namespace: 'hnxWebService',
  state: {
    title: '',
    footer: '',
    subSystems: []
  },
  reducers: {
    setData(state, { payload: {title, enTitle, footer, subSystems}}) {
      return { ...state, title, enTitle, footer, subSystems };
    },
  },
  effects: {
    *fetch({ _ }, { call, put }) {
      let title = '', enTitle='', footer= '', subSystems=[];
      const hnxWebService = yield call(bajaService.fetchHnxWebService);
      if(hnxWebService) {
        title = hnxWebService.getTitle();
        enTitle = hnxWebService.getEnTitle();
        footer = hnxWebService.getFooter();
        const subSystemsRoot = yield call(bajaService.Ord, 'station:|slot:/Services/HnxWebService/subSystemsRoot');
        if(subSystemsRoot) {
          memoryUtils.subSystemHandleToUrlMap = {};
          memoryUtils.SUBSYSTEM_TYPE = {};
          subSystems = yield call(bajaService.fetchNavChildren, subSystemsRoot);
          subSystems = yield call(bajaService.fetchSubSystems, subSystems);
          if(!subSystems) {
            subSystems = []
          }
        }
      }
      yield put({ type: 'setData', payload: {
          title, enTitle, footer, subSystems
        }});
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({ type: 'fetch'});
        }
      });
    },
  },
}
